<template>
    <el-dialog
        :visible.sync="dialogVisible"
        title="广告管理"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        width="500px"
    >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="分类" prop="cascaderPath">
                <el-cascader
                    v-model="formData.cascaderPath"
                    :options="adTypeList"
                    :props="{ value: 'id',label:'adTypeName' }"
                    :show-all-levels="false"
                    @change="handleChange"></el-cascader>
            </el-form-item>

            <el-form-item label="标题" prop="title">
                <el-input v-model="formData.title"/>
            </el-form-item>
            <el-form-item label="URL" prop="url">
                <el-input v-model="formData.url"/>
                <div class="form-tips">
                    示例：文章（/pages/index/article?id=###）、商品（/pages/index/yi_heng/GoodsDetail?mainGoodsId=###），把链接中的###替换为对应id即可
                </div>
            </el-form-item>
            <el-form-item label="图片" prop="image">
                <el-upload
                    class="avatar-uploader"
                    :action="apiHost + '/file/upload'"
                    :show-file-list="false"
                    :on-success="handleSuccess"
                    :headers="headers"
                >
                    <div v-if="formData.image">
                        <img :src="formData.image" class="avatar">
                    </div>
                    <i v-else class="el-icon-plus avatar-uploader-icon"/>

                </el-upload>
            </el-form-item>

            <el-form-item>
                <el-popconfirm :title="'确定保存吗？'" @onConfirm="submitForm()">
                    <el-button slot="reference" type="primary">保存</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import {AdApi} from '@/api/cms/Ad'
import {AdTypeApi} from '@/api/cms/AdType'
import {Common} from '@/utils/common'
import { getToken } from '@/utils/auth'


export default {
    name: 'CmsAdUpdate',
    components: {},
    data() {
        return {
            formData: {
                id: 0,
                adTypeId: 0,
                title: '',
                url: '',
                image: '',
                cascaderPath: []
            },
            rules: {
                cascaderPath: [
                    {required: true, message: '请选择广告分类', trigger: 'change', type: 'array'}
                ],
                title: [
                    {required: true, message: '请输入广告名称', trigger: 'blur'},
                    {min: 1, max: 60, message: '长度在 1 到 60 个字符', trigger: 'blur'}
                ]
            },
            dialogVisible: false,
            adTypeList: [], // 商品分类
            apiHost: process.env.VUE_APP_BASE_API,
            headers: { 'X-Token': getToken() }
        }
    },
    created() {

    },
    methods: {
        // 显示组件
        async showUpdate(data) {
            const that = this

            this.dialogVisible = true

            await AdTypeApi.getAllList().then((response) => {
                that.adTypeList = response
            })

            if (this.$refs['formRef'] !== undefined) {
                this.$refs['formRef'].resetFields()
            }

            this.$nextTick(() => {

                if (data.id > 0) {
                    that.formData = Common.assign(this.formData, data)
                    that.formData.cascaderPath = Common.getParentNode(that.adTypeList, that.adTypeList, data.adTypeId, []);
                } else {
                    this.formData.id = ''
                    this.formData.adTypeId = 0
                }
            })
        },
        handleSuccess(e) {
            this.formData.image = e.data
        },

        // 提交表单
        submitForm() {
            const that = this
            that.$refs['formRef'].validate((valid) => {
                if (valid) {
                    const submitData = Object.assign({}, that.formData)
                    submitData.adTypeId = submitData.cascaderPath[submitData.cascaderPath.length - 1]
                    if (submitData.id > 0) {
                        AdApi.edit(submitData).then(() => {
                            that.dialogVisible = false
                            that.$emit('refresh')
                        })
                    } else {
                        AdApi.add(submitData).then(() => {
                            that.dialogVisible = false
                            that.$emit('refresh')
                        })
                    }
                }
            })
        },
        handleChange(e) {
            this.formData.articleTypeId = e[e.length - 1]
        }
    }
}
</script>

<style>
</style>
